package com.lagou.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();

        String value = request.getPath().value();
        if(value.startsWith("/api/user/login") || value.startsWith("/api/user/register") || value.startsWith("/api/code/create")){
            return chain.filter(exchange);
        } else {
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            List<HttpCookie> token = cookies.get("token");
            if (token == null || token.size() <= 0) {
                //无权限访问
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.UNAUTHORIZED);//401
                DataBuffer wrap = response.bufferFactory().wrap("not auth".getBytes());
                return response.writeWith(Mono.justOrEmpty(wrap));
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
